
#include <BRender>
#include <BPainter>
#include <BFrustum>
#include <BScene>

#include "MainViewer.h"

MainViewer::MainViewer()
{

}
MainViewer::~MainViewer()
{

}

void MainViewer::setDebugCamera(BCamera* camera)
{
	_camera = camera;
}

void MainViewer::resizeEvent(const BEvent& event)
{
	BViewer::resizeEvent(event);
}

void drawFrustum(const BFrustum& frustum, BRender& render)
{
	render.setDepthTest(false);
	render.setLighting(false);
	render.setLineSmooth(true);

	BVector origin = frustum.origin();

	BVector v0 = frustum.v0();
	BVector v1 = frustum.v1();
	BVector v2 = frustum.v2();
	BVector v3 = frustum.v3();

	BVector v4 = frustum.v4();
	BVector v5 = frustum.v5();
	BVector v6 = frustum.v6();
	BVector v7 = frustum.v7();

	const BPlane& pfar = frustum.farPlane();
	const BPlane& pnear = frustum.nearPlane();
	const BPlane& pleft = frustum.leftPlane();
	const BPlane& pright = frustum.rightPlane();
	const BPlane& ptop = frustum.topPlane();
	const BPlane& pbottom = frustum.bottomPlane();

	render.setColor(0, 0, 255, 128);
	render.drawQuad(v0, v1, v2, v3);

	render.setColor(255, 255, 0, 128);
	render.drawTriangle(v0, v1, origin);
	render.drawTriangle(v1, v2, origin);
	render.drawTriangle(v2, v3, origin);
	render.drawTriangle(v3, v0, origin);

	render.setColor(0, 255, 0, 128);
	render.drawLine(v0, origin);
	render.drawLine(v1, origin);
	render.drawLine(v2, origin);
	render.drawLine(v3, origin);

	BVector v;
	render.setColor(255, 0, 0, 128);

	v = v0 + (v1-v0)/2;
	render.drawLine(v, v + pleft.normal() * 20);
	v = v1 + (v2-v1)/2;
	render.drawLine(v, v + pbottom.normal() * 20);
	v = v2 + (v3-v2)/2;
	render.drawLine(v, v + pright.normal() * 20);
	v = v3 + (v0-v3)/2;
	render.drawLine(v, v + ptop.normal() * 20);
	v = v0 + (v2-v0)/2;
	render.drawLine(v, v + pfar.normal() * 20);
}
void drawSpace(BNode* node, BRender& render)
{
	BSpace space = node->space();

	BVector v0 = space.v0();
	BVector v1 = space.v1();
	BVector v2 = space.v2();
	BVector v3 = space.v3();
	BVector v4 = space.v4();
	BVector v5 = space.v5();
	BVector v6 = space.v6();
	BVector v7 = space.v7();

	render.setColor(1, 1, 1);

	render.drawLine(v0, v1);
	render.drawLine(v1, v2);
	render.drawLine(v2, v3);
	render.drawLine(v3, v0);

	render.drawLine(v4, v5);
	render.drawLine(v5, v6);
	render.drawLine(v6, v7);
	render.drawLine(v7, v4);

	render.drawLine(v0, v4);
	render.drawLine(v1, v5);
	render.drawLine(v2, v6);
	render.drawLine(v3, v7);

}
void MainViewer::postRender(BRender& render)
{
	BString strSize("size is ");

	if(_camera && this->scene())
	{
		BList<BNodeHolder> nodelist;
		BScene* scene = this->scene();
		BFrustum frustum = _camera->frustum();
		for (int i = 0; i < scene->nodeCount(); i++)
		{
			BNode* node = scene->node(i);
			drawSpace(node, render);
		}
		if(nodelist.size())
			strSize += nodelist.size();

		drawFrustum(frustum, render);
	}

	BPainter painter(this);
	painter.setColor(BColor(1, 0, 0));
	painter.drawText(0, 0, strSize);
}
